package tests;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import peerToPeerFacebook.proj.IStorageProvider;

public class MemoryStorage implements IStorageProvider
{
	public Map<String, CharArrayWriter> files = new HashMap<String, CharArrayWriter>();
	public String crashFileName = null;
	
	public class StorageCrash extends RuntimeException
	{
		private static final long serialVersionUID = 1L;
		public StorageCrash() { super("This is exception to simulate crash in writting to file"); }
	}
	
	public MemoryStorage()
	{ }
	
	public void writeToFile(String name, String data) throws IOException
	{
		BufferedWriter writer = getWriter(name, false);
		writer.write(data);
		writer.newLine();
		writer.close();
	}
	
	public String[] readFile(String name) throws IOException
	{
		BufferedReader reader = getReader(name);
		List<String> data = new LinkedList<String>();
		String line = null;
		
		while ((line = reader.readLine()) != null)
			data.add(line);
		
		return (String[]) data.toArray(new String[data.size()]);
	}
	
	@Override
	public BufferedReader getReader(String filename) throws IOException
	{
		// See if the file exists
		if (!files.containsKey(filename))
			throw new FileNotFoundException();
		
		CharArrayWriter writer = files.get(filename);
		return new BufferedReader(new CharArrayReader(writer.toCharArray()));
	}

	@Override
	public BufferedWriter getWriter(String filename, boolean append)
	{
		if (filename.equals(crashFileName))
			throw new StorageCrash();
		
		if (!append || !files.containsKey(filename))
			files.put(filename, new CharArrayWriter());
		
		return new BufferedWriter(files.get(filename));
	}

	@Override
	public boolean fileExists(String name)
	{
		return files.containsKey(name);
	}

	@Override
	public boolean delete(String name) throws IOException
	{
		if (!files.containsKey(name))
			throw new FileNotFoundException();
		
		files.remove(name);
		return true;
	}
}
